package study.week05.bytebuddy.aop;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

public class AopTest {
    public static void main(String[] args) throws Exception {
        ServiceImpl service = new ByteBuddy()
                //父类
                .subclass(ServiceImpl.class)
                //代理的方法 这里是全部
                .method(ElementMatchers.any())
                //教给AspectAdvisor做代理
                .intercept(Advice.to(AspectAdvisor.class))
                //创建类对象
                .make()
                //加载
                .load(ServiceImpl.class.getClassLoader())
                .getLoaded()
                //创建实例
                .newInstance();
        System.out.println("生成的对象:"+service);
        //加了切面注解的方法
        service.methodAspect(123);
        //没加切面注解的方法
        service.methodNoAspect(456);
    }

    /**
     * 创建新的类
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private static void testCreatClass() throws IllegalAccessException, InstantiationException {
        DynamicType.Unloaded unloadedType = new ByteBuddy()
                .subclass(Object.class)
                .method(ElementMatchers.isToString())
                .intercept(FixedValue.value("Hello World ByteBuddy!"))
                .make();

        Class<?> dynamicType = unloadedType.load(Object.class
                .getClassLoader())
                .getLoaded();
        String string = dynamicType.newInstance().toString();
        System.out.println(string);
    }

}
